package com.definity.toolkit.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.cage.Cage;
import com.github.cage.GCage;

public class CaptchaServlet extends HttpServlet {

	private static final long serialVersionUID = -5997605256170521386L;

	public static final String CAPTCHA_TEXT = "gen-cap";
	
	private Cage cage;

	@Override
	public void init() throws ServletException {
		super.init();
		
		this.cage = new GCage();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String token = cage.getTokenGenerator().next();
		token = token.substring(0, 5);
		
		req.getSession(true).setAttribute(CAPTCHA_TEXT, token);
		
	    resp.setContentType("image/" + cage.getFormat());
	    resp.setHeader("Cache-Control", "no-cache, no-store");
	    resp.setHeader("Pragma", "no-cache");
	    long time = System.currentTimeMillis();
	    resp.setDateHeader("Last-Modified", time);
	    resp.setDateHeader("Date", time);
	    resp.setDateHeader("Expires", time);
	    cage.draw(token, resp.getOutputStream());
	}

}
